package com.ruoyi.business.controller;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.business.domain.dto.TrainSeatHierarchyDTO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.TrainSeat;
import com.ruoyi.business.service.ITrainSeatService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 火车座位Controller
 *
 * @author ruoyi
 * @date 2025-03-06
 */
@RestController
@RequestMapping("/base/train-seat")
public class TrainSeatController extends BaseController
{
    @Autowired
    private ITrainSeatService trainSeatService;

    /**
     * 查询火车座位列表
     */
    @PreAuthorize("@ss.hasPermi('base:train-seat:list')")
    @GetMapping("/list")
    public TableDataInfo list(TrainSeat trainSeat)
    {
        startPage();
        List<TrainSeat> list = trainSeatService.selectTrainSeatList(trainSeat);
        return getDataTable(list);
    }

    /**
     * 导出火车座位列表
     */
    @PreAuthorize("@ss.hasPermi('base:train-seat:export')")
    @Log(title = "火车座位", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TrainSeat trainSeat)
    {
        List<TrainSeat> list = trainSeatService.selectTrainSeatList(trainSeat);
        ExcelUtil<TrainSeat> util = new ExcelUtil<TrainSeat>(TrainSeat.class);
        util.exportExcel(response, list, "火车座位数据");
    }

    /**
     * 获取火车座位详细信息
     */
    @PreAuthorize("@ss.hasPermi('base:train-seat:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(trainSeatService.selectTrainSeatById(id));
    }

    /**
     * 新增火车座位
     */
    @PreAuthorize("@ss.hasPermi('base:train-seat:add')")
    @Log(title = "火车座位", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TrainSeat trainSeat)
    {
        return toAjax(trainSeatService.insertTrainSeat(trainSeat));
    }

    /**
     * 修改火车座位
     */
    @PreAuthorize("@ss.hasPermi('base:train-seat:edit')")
    @Log(title = "火车座位", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TrainSeat trainSeat)
    {
        return toAjax(trainSeatService.updateTrainSeat(trainSeat));
    }

    /**
     * 删除火车座位
     */
    @PreAuthorize("@ss.hasPermi('base:train-seat:remove')")
    @Log(title = "火车座位", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(trainSeatService.deleteTrainSeatByIds(ids));
    }

    /**
     * 清空火车座位数据
     */
    @PreAuthorize("@ss.hasPermi('base:train-seat:remove')")
    @Log(title = "火车座位", businessType = BusinessType.CLEAN)
    @PostMapping("/clear")
    public AjaxResult clear(@RequestBody Map<String, String> passwordMap)
    {
        String password = passwordMap.get("password");
        System.out.println("密码：" + password);
        if (!"admin123".equals(password)) {
            return AjaxResult.error("密码错误");
        }
        return toAjax(trainSeatService.clearTrainSeat());
    }

    /**
     * 查询分组后的火车座位列表
     */
    @PreAuthorize("@ss.hasPermi('base:train-seat:list')")
    @GetMapping("/groupList")
    public AjaxResult groupList(TrainSeat trainSeat) {
        try {
            // 获取分页信息
            Integer pageNum = 1;
            Integer pageSize = 10;

            if (trainSeat.getParams() != null) {
                if (trainSeat.getParams().get("pageNum") != null) {
                    pageNum = Integer.parseInt(trainSeat.getParams().get("pageNum").toString());
                }
                if (trainSeat.getParams().get("pageSize") != null) {
                    pageSize = Integer.parseInt(trainSeat.getParams().get("pageSize").toString());
                }
            }

            // 移除分页限制，查询符合条件的所有数据
            TrainSeat queryParam = new TrainSeat();
            if (trainSeat.getTrainCode() != null) {
                queryParam.setTrainCode(trainSeat.getTrainCode());
            }
            // 不设置分页参数，获取所有符合条件的数据
            List<TrainSeat> list = trainSeatService.selectTrainSeatList(queryParam);

            // 按列车和车厢分组
            Map<String, Map<Long, List<TrainSeat>>> groupedData = new HashMap<>();

            // 将数据按照trainCode和carriageIndex分组
            for (TrainSeat seat : list) {
                String trainCode = seat.getTrainCode();
                Long carriageIndex = seat.getCarriageIndex();

                if (trainCode == null || carriageIndex == null) {
                    continue; // 跳过无效数据
                }

                if (!groupedData.containsKey(trainCode)) {
                    groupedData.put(trainCode, new HashMap<>());
                }

                Map<Long, List<TrainSeat>> carriages = groupedData.get(trainCode);
                if (!carriages.containsKey(carriageIndex)) {
                    carriages.put(carriageIndex, new ArrayList<>());
                }

                carriages.get(carriageIndex).add(seat);
            }

            // 获取所有列车编号并排序
            List<String> trainCodes = new ArrayList<>(groupedData.keySet());
            Collections.sort(trainCodes);

            // 计算列车总数
            int trainTotal = trainCodes.size();

            // 计算分页 (仅对列车进行分页)
            int fromIndex = (pageNum - 1) * pageSize;
            int toIndex = Math.min(fromIndex + pageSize, trainCodes.size());

            // 对分页范围进行校验
            if (fromIndex >= trainCodes.size() && trainCodes.size() > 0) {
                fromIndex = 0;
                toIndex = Math.min(pageSize, trainCodes.size());
            }

            // 获取当前页的列车编号
            List<String> pageTrainCodes = (fromIndex < toIndex && trainCodes.size() > 0)
                    ? trainCodes.subList(fromIndex, toIndex)
                    : new ArrayList<>();

            // 构建返回结果
            List<TrainSeatHierarchyDTO.TrainGroup> result = new ArrayList<>();

            for (String trainCode : pageTrainCodes) {
                Map<Long, List<TrainSeat>> carriagesMap = groupedData.get(trainCode);
                if (carriagesMap == null) continue;

                TrainSeatHierarchyDTO.TrainGroup trainGroup = new TrainSeatHierarchyDTO.TrainGroup();
                trainGroup.setTrainCode(trainCode);

                List<TrainSeatHierarchyDTO.CarriageGroup> carriages = new ArrayList<>();

                // 确保处理所有车厢
                for (Map.Entry<Long, List<TrainSeat>> carriageEntry : carriagesMap.entrySet()) {
                    Long carriageIndex = carriageEntry.getKey();
                    List<TrainSeat> seats = carriageEntry.getValue();

                    if (seats == null || seats.isEmpty()) continue;

                    TrainSeatHierarchyDTO.CarriageGroup carriageGroup = new TrainSeatHierarchyDTO.CarriageGroup();
                    carriageGroup.setCarriageIndex(carriageIndex);

                    // 按座序排序
                    seats.sort((a, b) -> {
                        Long aIndex = a.getCarriageSeatIndex();
                        Long bIndex = b.getCarriageSeatIndex();
                        if (aIndex == null) return 1;
                        if (bIndex == null) return -1;
                        return aIndex.compareTo(bIndex);
                    });

                    carriageGroup.setSeats(seats);
                    carriages.add(carriageGroup);
                }

                // 按车厢序号排序
                carriages.sort((a, b) -> {
                    Long aIndex = a.getCarriageIndex();
                    Long bIndex = b.getCarriageIndex();
                    if (aIndex == null) return 1;
                    if (bIndex == null) return -1;
                    return aIndex.compareTo(bIndex);
                });

                trainGroup.setCarriages(carriages);
                result.add(trainGroup);
            }

            // 使用若依框架的AjaxResult结构
            AjaxResult ajaxResult = AjaxResult.success(result);
            ajaxResult.put("total", trainTotal);  // 添加列车总数用于分页

            return ajaxResult;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取分组数据失败: " + e.getMessage());
        }
    }
}
